package com.hmall.search.feign;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.ItemDTO;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
public class feginText {
    @Autowired
    private ItemClient  itemClient;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    private  static  final ObjectMapper MAPPER= new ObjectMapper();

    @Test
    public void test() throws IOException {
        int page = 1;
        while (true) {
            PageDTO<ItemDTO>  pageDTO = itemClient.page(page,500);
            List<ItemDTO> list = pageDTO.getList();
            if (list.size()<=0){
                break;
            }
            BulkRequest request = new BulkRequest();
            for (ItemDTO itemDTO : list) {
                ItemDoc itemDoc = new ItemDoc(itemDTO);
                request.add( new IndexRequest("item")
                        .id(itemDoc.getId().toString())
                        .source(MAPPER.writer().writeValueAsString(itemDoc), XContentType.JSON)
                );
            }
            BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
            System.out.println("Response="+bulk);
            page++;
        }
    }


}
